<template>
  <view class="word-set-container">
    <view class="header">
      <h1>单词集管理</h1>
      <button class="btn btn-primary" @click="showCreateModal = true">创建单词集</button>
    </view>

    <view class="word-set-list">
      <view class="word-set-card" v-for="wordSet in wordSets" :key="wordSet.id">
        <view class="word-set-header">
          <h2>{{ wordSet.name }}</h2>
          <view class="word-set-actions">
            <button class="btn btn-secondary" @click="editWordSet(wordSet)">编辑</button>
            <button class="btn btn-danger" @click="deleteWordSet(wordSet.id)">删除</button>
          </view>
        </view>
        
        <view class="word-set-info">
          <span class="word-count">{{ wordSet.wordCount }} 个单词</span>
          <span class="created-at">创建于 {{ formatDate(wordSet.createdAt) }}</span>
        </view>
        
        <view class="word-set-preview">
          <view class="words-preview">
            <span v-for="(word, index) in wordSet.previewWords" :key="index" class="word-tag">
              {{ word }}
            </span>
            <span v-if="wordSet.wordCount > wordSet.previewWords.length" class="more-words">
              +{{ wordSet.wordCount - wordSet.previewWords.length }} 个单词
            </span>
          </view>
        </view>
        
        <view class="word-set-footer">
          <button class="btn btn-primary" @click="goToLearning(wordSet.id)">开始学习</button>
          <button class="btn btn-secondary" @click="viewWordSetDetail(wordSet.id)">查看详情</button>
        </view>
      </view>
    </view>

    <!-- 创建/编辑单词集模态框 -->
    <view class="modal" v-if="showCreateModal || showEditModal" @click.self="closeModal">
      <view class="modal-content">
        <view class="modal-header">
          <h2>{{ editingWordSet ? '编辑单词集' : '创建单词集' }}</h2>
          <button class="close-btn" @click="closeModal">&times;</button>
        </view>
        
        <view class="modal-body">
          <form @submit.prevent="saveWordSet">
            <view class="form-group">
              <label for="wordSetName">单词集名称</label>
              <input
                type="text"
                id="wordSetName"
                v-model="formData.name"
                required
                placeholder="请输入单词集名称"
              />
            </view>
            
            <view class="form-group">
              <label for="wordSetDescription">描述（可选）</label>
              <textarea
                id="wordSetDescription"
                v-model="formData.description"
                placeholder="请输入单词集描述"
                rows="3"
              ></textarea>
            </view>
            
            <view class="form-group">
              <label for="wordSetLanguage">语言</label>
              <select id="wordSetLanguage" v-model="formData.language">
                <option value="en">英语</option>
                <option value="zh">中文</option>
                <option value="ja">日语</option>
                <option value="ko">韩语</option>
                <option value="fr">法语</option>
                <option value="de">德语</option>
                <option value="es">西班牙语</option>
                <option value="other">其他</option>
              </select>
            </view>
            
            <view class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">
                {{ editingWordSet ? '保存' : '创建' }}
              </button>
            </view>
          </form>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  name: 'WordSet',
  setup() {
    // 在uni-app中使用原生导航API，不需要router实例
    
    // 状态管理
    const wordSets = ref([])
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const editingWordSet = ref(null)
    
    // 表单数据
    const formData = ref({
      name: '',
      description: '',
      language: 'en'
    })
    
    // 初始化单词集列表
    const initializeWordSets = async () => {
      try {
        console.log('开始加载单词集列表...')
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 直接使用模拟数据
        wordSets.value = generateMockWordSets()
        
        console.log('单词集列表加载成功')
      } catch (error) {
        console.error('获取单词集列表失败', error)
        // 使用模拟数据作为备选
        wordSets.value = generateMockWordSets()
      }
    }
    
    // 生成模拟单词集数据
    const generateMockWordSets = () => {
      return [
        {
          id: 1,
          name: '托福核心词汇',
          description: '托福考试必备的核心词汇，包含高频出现的单词',
          language: 'en',
          wordCount: 500,
          createdAt: '2023-09-15T10:30:00Z',
          previewWords: ['aberration', 'abjure', 'ablution', 'abnegation', 'abominate']
        },
        {
          id: 2,
          name: '日常英语会话',
          description: '日常生活中常用的英语会话词汇',
          language: 'en',
          wordCount: 300,
          createdAt: '2023-10-05T14:20:00Z',
          previewWords: ['greet', 'introduce', 'thank', 'apologize', 'request']
        },
        {
          id: 3,
          name: '商务英语词汇',
          description: '商务场合中常用的专业英语词汇',
          language: 'en',
          wordCount: 450,
          createdAt: '2023-10-20T09:15:00Z',
          previewWords: ['negotiate', 'contract', 'investment', 'profit', 'marketing']
        },
        {
          id: 4,
          name: '旅游英语常用词',
          description: '出国旅游时必备的实用英语词汇',
          language: 'en',
          wordCount: 200,
          createdAt: '2023-11-02T16:45:00Z',
          previewWords: ['airport', 'hotel', 'restaurant', 'attraction', 'transportation']
        },
        {
          id: 5,
          name: '计算机专业词汇',
          description: '计算机科学和编程领域的专业词汇',
          language: 'en',
          wordCount: 600,
          createdAt: '2023-11-15T11:30:00Z',
          previewWords: ['algorithm', 'database', 'function', 'variable', 'interface']
        }
      ]
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    }
    
    // 打开编辑单词集模态框
    const editWordSet = (wordSet) => {
      editingWordSet.value = wordSet
      formData.value = {
        name: wordSet.name,
        description: wordSet.description || '',
        language: wordSet.language || 'en'
      }
      showEditModal.value = true
    }
    
    // 删除单词集
    const deleteWordSet = async (id) => {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个单词集吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 模拟API调用
              await new Promise(resolve => setTimeout(resolve, 500))
              
              // API调用成功后更新本地数据
              wordSets.value = wordSets.value.filter(wordSet => wordSet.id !== id)
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } catch (error) {
              console.error('删除单词集失败', error)
              uni.showToast({
                title: '删除失败: ' + (error.message || '未知错误'),
                icon: 'none'
              })
            }
          }
        }
      })
    }
    
    // 保存单词集（创建或编辑）
    const saveWordSet = async () => {
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        if (editingWordSet.value) {
          // 编辑单词集
          // 模拟成功响应
          const updatedWordSet = {
            ...editingWordSet.value,
            ...formData.value
          }
          
          // API调用成功后更新本地数据
          const index = wordSets.value.findIndex(wordSet => wordSet.id === editingWordSet.value.id)
          if (index !== -1) {
            wordSets.value[index] = updatedWordSet
          }
          
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          })
        } else {
          // 创建新单词集
          // 模拟成功响应
          const newWordSet = {
            id: Date.now(),
            ...formData.value,
            wordCount: 0,
            createdAt: new Date().toISOString(),
            previewWords: []
          }
          
          // API调用成功后添加到本地数据
          wordSets.value.unshift(newWordSet)
          
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
        }
        
        closeModal()
      } catch (error) {
        console.error(editingWordSet.value ? '更新单词集失败' : '创建单词集失败', error)
        uni.showToast({
          title: '操作失败: ' + (error.message || '未知错误'),
          icon: 'none'
        })
      }
    }
    
    // 关闭模态框
    const closeModal = () => {
      showCreateModal.value = false
      showEditModal.value = false
      editingWordSet.value = null
      formData.value = {
        name: '',
        description: '',
        language: 'en'
      }
    }
    
    // 前往学习页面
    const goToLearning = (wordSetId) => {
      uni.navigateTo({
        url: `/pages/wordlearning/WordLearning?wordSetId=${wordSetId}`
      })
    }
    
    // 查看单词集详情
    const viewWordSetDetail = (wordSetId) => {
      // 如果word-set-detail页面存在，则导航过去，否则提示暂未实现
      uni.showToast({
        title: '查看详情功能暂未实现',
        icon: 'none'
      })
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeWordSets()
    })
    
    return {
      wordSets,
      showCreateModal,
      showEditModal,
      editingWordSet,
      formData,
      formatDate,
      editWordSet,
      deleteWordSet,
      saveWordSet,
      closeModal,
      goToLearning,
      viewWordSetDetail
    }
  }
}
</script>

<style scoped>
.word-set-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #333;
  margin: 0;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background-color: #7f8c8d;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background-color: #c0392b;
}

.word-set-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.word-set-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.word-set-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.word-set-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.word-set-header h2 {
  color: #2c3e50;
  margin: 0;
  font-size: 18px;
  flex: 1;
  margin-right: 10px;
}

.word-set-actions {
  display: flex;
  gap: 8px;
}

.word-set-actions .btn {
  padding: 6px 12px;
  font-size: 12px;
}

.word-set-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 13px;
  color: #666;
}

.word-set-preview {
  margin-bottom: 20px;
}

.words-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.word-tag {
  display: inline-block;
  background-color: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.more-words {
  font-size: 12px;
  color: #999;
  font-style: italic;
}

.word-set-footer {
  display: flex;
  gap: 10px;
}

.word-set-footer .btn {
  flex: 1;
  padding: 10px 15px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .word-set-list {
    grid-template-columns: 1fr;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .word-set-header {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .word-set-actions {
    justify-content: flex-end;
  }
}
</style>